<template>
  <div>
    <h3>购物车</h3>
    <el-table :data="tableData" border @selection-change="toggleAll">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="goodsInfo.name" label="商品名称"></el-table-column>
      <el-table-column prop="goodsInfo.detail" label="商品描述"></el-table-column>
      <el-table-column prop="goodsInfo.unit" label="商品单位"></el-table-column>
      <el-table-column prop="goodsInfo.price" label="单价"></el-table-column>
      <el-table-column label="数量">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.cartInfo.goodsCount" @input="updatePrice(scope.row)" size="small"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="subtotal" label="小计"></el-table-column>
      <el-table-column prop="cartInfo.createTime" label="加入时间"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteRow(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!---分页组件-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="pageSizeList"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
    <div id="footer">
      <div class="foot_op">
        <el-button type="danger" @click="deleteBatch">批量删除</el-button>
      </div>
      <div class="foot_total">
        <div class="amout-sum">
          <span class="txt">已选商品</span>
          <strong id="selected_amout" ref="selectedAmount"></strong>
          <span class="txt">件</span>
        </div>
        <div class="price-sum">
          <span class="txt">合计（不含运费）：</span>
          <strong class="selected_price" ref="selectedPrice">0.00</strong>
        </div>
        <div class="btn-area">
          <a class="btn-sumbit"  @click="buyNow()">结&nbsp;算</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //用户ID
      sysUsersId: '',
      //当前页号
      pageNo: 1,
      // 当前页大小
      pageSize: 5,
      // 总记录数
      total: 0,
      // 页大小列表
      pageSizeList: [5, 10, 20],
      tableData: [],
      totalPrice:'',
      selectedRows: [],
      isAllChecked: false,
    }
  },
  computed: {
    totalQuantity() {
      return this.tableData.reduce((total, item) => {
        return total + item.cartInfo.goodsCount;
      }, 0);
    },
    /*totalPrice() {
      return this.tableData.reduce((total, item) => {
        return total + item.goodsInfo.price * item.cartInfo.goodsCount;
      }, 0);
    }*/
  },
  methods: {
    // 表单查询
    search() {
      // 查询
      this.pageNo = 1
      this.searchCartInfo()
    },
    // 页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.searchCartInfo()
    },

    // 页号改变
    handleCurrentChange(val) {
      this.pageNo = val
      // 重新查询
      this.searchCartInfo()
    },
    async searchCartInfo() {
      this.sysUsersId=this.$store.state.user.sysUsersId
      console.log(this.sysUsersId)
      const {data: res} = await this.$http.post(`/cartInfo/selCarts/${this.sysUsersId}/${this.pageNo}/${this.pageSize}`)
      this.tableData = res.rows
      console.log(res)
      this.total = res.total
    },
    //全选和取消
    toggleAll(selection) {
      this.isAllChecked = selection.length === this.tableData.length;
      this.tableData.forEach(row => {
        row.cartInfo.checked = this.isAllChecked;
      });
      this.selectedRows = selection;

      // 更新总选定数量
      this.$nextTick(() => {
        this.updateSelectedQuantityAndPrice();
      });
    },
    //通过数量计算价格
    updatePrice(row) {
      this.$set(row, 'subtotal', row.goodsInfo.price * row.cartInfo.goodsCount);
      this.totalPrice = this.tableData.reduce((total, item) => {
        return total + item.goodsInfo.price * item.cartInfo.goodsCount;
      }, 0);
    },
    updateSelectedQuantityAndPrice() {
      let selectedQuantity = 0;
      let totalPrice = 0;
      this.selectedRows.forEach(row => {
        selectedQuantity += row.cartInfo.goodsCount;
        totalPrice += row.goodsInfo.price * row.cartInfo.goodsCount;
      });

      // 更新UI元素
      this.$refs.selectedAmount.innerText = selectedQuantity;
      this.$refs.selectedPrice.innerText = totalPrice.toFixed(2);
    },
    //单个删除
    deleteRow(row) {
      this.$confirm('是否确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //确定
        let cartId=row.cartInfo.cartId
        const { data: res } = await this.$http.post(`/cartInfo/delCartInfo/${cartId}`);
        this.$message.success("删除成功！");
        //界面刷新
        this.searchCartInfo();
        // 更新选定的数量和价格
        this.updateSelectedQuantityAndPrice();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //批量删除
    async deleteBatch() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的商品！');
        return;
      }

      this.$confirm('是否确认批量删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let cartIds = this.selectedRows.map(row => row.cartInfo.cartId);
        const { data: res } = await this.$http.post(`/cartInfo/delBatchCartInfo`,cartIds);
        this.$message.success("批量删除成功！");
        this.searchCartInfo();
        // 更新选定的数量和价格
        this.updateSelectedQuantityAndPrice();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消批量删除'
        });
      });
    },
    async buyNow() {
      // 检查是否有选中的商品项
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要购买的商品！');
        return;
      }

      //准备要传递到结算页面的数据
      const selectedProducts = this.selectedRows.map(row => ({
        name: row.goodsInfo.name,
        price: row.goodsInfo.price,
        amount: row.cartInfo.goodsCount,
        detail:row.goodsInfo.detail,
        unit:row.goodsInfo.unit,
        goodsId:row.goodsInfo.id,
        cartId:row.cartInfo.cartId
      }));

      const totalSelectedQuantity = this.selectedRows.reduce((total, row) => {
        return total + row.cartInfo.goodsCount;
      }, 0);
      const totalPrice = this.selectedRows.reduce((total, row) => {
        return total + row.goodsInfo.price * row.cartInfo.goodsCount;
      }, 0);

      // 导航到结算页面，并将数据作为路由参数或查询参数传递
      this.$router.push({
        name: 'checkout',
        params: {
          selectedProducts,
          totalSelectedQuantity,
          totalPrice
        }
      });
    },
  },
  created() {
    this.searchCartInfo();
  }
}
</script>

<style scoped>
.product-info img {
  width: 50px;
  height: 50px;
  object-fit: cover;
  margin-right: 10px;
}

#footer{
  width: 89%;
  height: 50px;
  position: fixed;
  bottom: 0;
  left:11%;
  background: #E5E5E5;
  z-index: 9999;
}
#footer div{
  display: inline-block;
}
#footer>.foot_select{
  width: 50px;
  height: 50px;
  line-height: 50px;
  padding-left: 5px;
  cursor: pointer;
  font-size: 14px;
}
.foot_select input,.foot_select label{
  cursor: pointer;
}
.foot_op{
  line-height: 50px;
  height: 50px;
}
.foot_op>.foot_remove{
  margin-left: 25px;
  font-size: 14px;
  cursor: pointer;
}
.foot_remove:hover{
  color: #f40;
}
.foot_total{
  float: right;
}
.foot_total>.amout-sum{
  cursor: pointer;
  height: 50px;
  color: #3c3c3c;
}
.foot_total .txt{
  line-height: 50px;
  font-size: 14px;
}
.amout-sum>#selected_amout{
  padding: 0 5px;
  color: #f40;
  font-weight: 700;
  font-size: 18px;
}
.price-sum{
  margin-left: 50px;
}
.price-sum>.selected_price{
  color: #f40;
  font-weight: 700;
  font-size: 20px;
  line-height: 50px;
}
.btn-area>.btn-sumbit{
  display: inline-block;
  background: #B0B0B0;
  color: #fff;
  border-left: 1px solid #e7e7e7;
  width: 119px;
  height: 50px;
  cursor: pointer;
  text-align: center;
  line-height: 50px;
  font-size: 20px;
}
.btn-area>.btn-sumbit.btn-allow{
  background: #f22d00;
  cursor: pointer;
}
</style>